from fastapi import APIRouter, Depends, Form, Request, Query, HTTPException
from fastapi.responses import HTMLResponse, RedirectResponse, JSONResponse
from sqlalchemy.orm import Session
from typing import Optional
from pydantic import BaseModel
from ..models import get_db, SearchEngine, User, WebsiteConfig
from ..auth import get_current_user
from ..utils import paginate_query
import os
from datetime import datetime
from fastapi.templating import Jinja2Templates

# 状态切换请求模型
class ToggleStatusRequest(BaseModel):
    new_status: bool

router = APIRouter()

# 获取模板目录
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
templates = Jinja2Templates(directory=os.path.join(BASE_DIR, "templates"))

# 搜索引擎列表页面
@router.get("/search-engines", response_class=HTMLResponse)
async def admin_search_engines(
    request: Request, 
    page: int = Query(1, ge=1), 
    db: Session = Depends(get_db), 
    current_user: User = Depends(get_current_user)
):
    query = db.query(SearchEngine).order_by(SearchEngine.id)
    pagination = paginate_query(query, page, 20)
    
    # 获取网站配置
    config = db.query(WebsiteConfig).first()
    if not config:
        config = WebsiteConfig(background_effect="gradient")
    
    return templates.TemplateResponse("admin/search-engines.html", {
        "request": request, 
        "search_engines": pagination["items"],
        "current_page": pagination["current_page"],
        "total_pages": pagination["total_pages"],
        "total_items": pagination["total_items"],
        "page_size": pagination["page_size"],
        "current_user": current_user,
        "config": config
    })

# 添加搜索引擎页面
@router.get("/search-engines/add", response_class=HTMLResponse)
async def admin_add_search_engine(
    request: Request, 
    db: Session = Depends(get_db), 
    current_user: User = Depends(get_current_user)
):
    # 获取网站配置
    config = db.query(WebsiteConfig).first()
    if not config:
        config = WebsiteConfig(background_effect="stars")
    return templates.TemplateResponse(
        "admin/search-engine-form.html", 
        {"request": request, "engine": None, "action": "add", "current_user": current_user, "config": config}
    )

# 编辑搜索引擎页面
@router.get("/search-engines/edit/{search_engine_id}", response_class=HTMLResponse)
async def admin_edit_search_engine(
    request: Request, 
    search_engine_id: int, 
    db: Session = Depends(get_db), 
    current_user: User = Depends(get_current_user)
):
    search_engine = db.query(SearchEngine).filter(SearchEngine.id == search_engine_id).first()
    if not search_engine:
        raise HTTPException(status_code=404, detail="搜索引擎不存在")
    # 获取网站配置
    config = db.query(WebsiteConfig).first()
    if not config:
        config = WebsiteConfig(background_effect="stars")
    return templates.TemplateResponse(
        "admin/search-engine-form.html", 
        {"request": request, "engine": search_engine, "action": "edit", "current_user": current_user, "config": config}
    )

# 保存搜索引擎
@router.post("/search-engines/save")
async def save_search_engine(
    request: Request,
    id: Optional[int] = Form(None),
    name: str = Form(...),
    url: str = Form(...),
    existing_icon: Optional[str] = Form(None),
    remove_icon: bool = Form(False),
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    # 处理文件上传
    form_data = await request.form()
    icon_path = None
    
    # 如果是编辑模式且没有上传新图标
    if id and not remove_icon:
        if 'icon_file' in form_data and form_data['icon_file'].filename:
            # 处理新上传的图标
            file = form_data['icon_file']
            # 确保上传目录存在
            upload_dir = os.path.join(BASE_DIR, "static", "uploads", "icons")
            os.makedirs(upload_dir, exist_ok=True)
            
            # 生成唯一文件名
            timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
            file_extension = os.path.splitext(file.filename)[1]
            filename = f"{timestamp}{file_extension}"
            file_path = os.path.join(upload_dir, filename)
            
            # 保存文件
            content = await file.read()
            with open(file_path, "wb") as f:
                f.write(content)
            
            # 保存相对路径
            icon_path = f"/static/uploads/icons/{filename}"
        else:
            # 使用现有图标
            icon_path = existing_icon
    # 如果是添加模式且上传了图标
    elif not id and 'icon_file' in form_data and form_data['icon_file'].filename:
        file = form_data['icon_file']
        # 确保上传目录存在
        upload_dir = os.path.join(BASE_DIR, "static", "uploads", "icons")
        os.makedirs(upload_dir, exist_ok=True)
        
        # 生成唯一文件名
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        file_extension = os.path.splitext(file.filename)[1]
        filename = f"{timestamp}{file_extension}"
        file_path = os.path.join(upload_dir, filename)
        
        # 保存文件
        content = await file.read()
        with open(file_path, "wb") as f:
            f.write(content)
        
        # 保存相对路径
        icon_path = f"/static/uploads/icons/{filename}"
    # 如果选择了移除图标
    elif remove_icon:
        icon_path = None
    
    if id:
        search_engine = db.query(SearchEngine).filter(SearchEngine.id == id).first()
        if not search_engine:
            raise HTTPException(status_code=404, detail="搜索引擎不存在")
        search_engine.name = name
        search_engine.url = url
        search_engine.icon = icon_path
    else:
        search_engine = SearchEngine(
            name=name,
            url=url,
            icon=icon_path
        )
        db.add(search_engine)
    db.commit()
    return RedirectResponse(url="/admin/search-engines", status_code=302)

# 删除搜索引擎
@router.post("/search-engines/delete/{search_engine_id}")
async def delete_search_engine(
    search_engine_id: int,
    request: Request,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    search_engine = db.query(SearchEngine).filter(SearchEngine.id == search_engine_id).first()
    
    # 检查是否是异步请求
    is_ajax = request.headers.get("X-Requested-With") == "XMLHttpRequest"
    
    if not search_engine:
        if is_ajax:
            return {"success": False, "message": "搜索引擎不存在"}
        else:
            raise HTTPException(status_code=404, detail="搜索引擎不存在")
    
    db.delete(search_engine)
    db.commit()
    
    if is_ajax:
        return {"success": True, "message": "删除成功"}
    else:
        return RedirectResponse(url="/admin/search-engines?message=删除成功", status_code=302)

# 批量删除搜索引擎
@router.post("/search-engines/batch-delete")
async def batch_delete_search_engines(
    request: Request,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    form_data = await request.form()
    search_engine_ids = form_data.getlist("search_engine_ids")
    
    # 检查是否是异步请求
    is_ajax = request.headers.get("X-Requested-With") == "XMLHttpRequest"
    
    if not search_engine_ids:
        if is_ajax:
            return {"success": False, "message": "请选择要删除的搜索引擎"}
        else:
            return RedirectResponse(url="/admin/search-engines?message=请选择要删除的搜索引擎", status_code=302)
    
    # 将字符串ID列表转换为整数列表
    search_engine_ids = [int(id) for id in search_engine_ids]
    # 批量删除选中的搜索引擎
    db.query(SearchEngine).filter(SearchEngine.id.in_(search_engine_ids)).delete(synchronize_session=False)
    db.commit()
    
    if is_ajax:
        return {"success": True, "message": "批量删除成功"}
    else:
        return RedirectResponse(url="/admin/search-engines?message=批量删除成功", status_code=302)

# 切换搜索引擎状态
@router.post("/search-engines/toggle-status/{search_engine_id}")
async def toggle_search_engine_status(
    search_engine_id: int,
    request_data: ToggleStatusRequest,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    try:
        # 查找搜索引擎
        search_engine = db.query(SearchEngine).filter(SearchEngine.id == search_engine_id).first()
        
        if not search_engine:
            return JSONResponse(
                content={"success": False, "message": "搜索引擎不存在"},
                status_code=404
            )
        
        # 更新状态为前端请求的状态
        search_engine.status = request_data.new_status
        db.commit()
        
        status_text = "启用" if search_engine.status else "禁用"
        return JSONResponse(
            content={"success": True, "message": f"搜索引擎{status_text}成功", "new_status": search_engine.status}
        )
    except Exception as e:
        db.rollback()
        return JSONResponse(
            content={"success": False, "message": f"状态切换失败: {str(e)}"},
            status_code=500
        )